﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraEditors;
using DevExpress.XtraPivotGrid;
using csds;
using NewStation;
using View.Statistics;
using View.History;
using View.Report;
using DevExpress.XtraBars.Helpers;
using View.Table;
using View.Journal;
using System.Threading;
using TestMySqlConnetPoll;
using System.Collections;
using View.Alarm;
using View.Common;


namespace View
{
    public partial class MainForm : XtraForm
    {
        private Thread flashRealThread; //实时值刷新线程
        private bool ThreadStop = false;
        public MainForm()
        {
            InitializeComponent();

            splashScreenManager1.ShowWaitForm();


            flashRealThread = new Thread(FlashRealData);
            flashRealThread.Start();
            //popupMenu1
            SkinHelper.InitSkinPopupMenu(popupMenu1);

            //开始设置时间
            timer_Clock.Start();
            Timer_Clock_Tick(null, null);

            timer_real.Enabled = true;

            c_ReceiveData.NewAlarmEvent += RealTimeValue_NewAlarmEvent;

            //this.dockPanel_Server.Hide();

            ReadStationCfg();
            splashScreenManager1.CloseWaitForm();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            ThreadStop = true;
            //c_Device.StopAllThread();
            System.Diagnostics.Process.GetCurrentProcess().Kill();
            base.OnClosing(e);
        }

        /// <summary>
        /// 刷新实时值
        /// </summary>
        private void FlashRealData()
        {
            while (!ThreadStop)
            {
                //c_RealTimeValue.RefreshRealTimeData();
                BitArray tempdigitsstatus = new BitArray(4046);
                int index = 0;
                for (int i = 0; i < c_RealTimeValue.ReceiveKGLData.Value.Count; i++)
                {
                    for (int j = 0; j < 8; j++)
                    {
                        if (index >= c_RealTimeValue.ReceiveKGLData.kglNum)
                            break;
                        tempdigitsstatus[index] = (c_RealTimeValue.ReceiveKGLData.Value[i] & (int)Math.Pow(2, j)) == (int)Math.Pow(2, j) ? true : false;
                        index++;
                    }
                }

                if (sform != null)
                    sform.changetest(tempdigitsstatus);

                Thread.Sleep(1000);
            }
        }

        private void btnServer_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //XtraForm1 form = new XtraForm1();
            //form.MdiParent = this;
            //form.Show();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnAnalysis_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                XtraFormReport rep = new XtraFormReport() { MdiParent = this };
                rep.Show();
            }
            catch(Exception ex) { }
        }

        /// <summary>
        /// 时间更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Clock_Tick(object sender, EventArgs e)
        {
            lblRealText.Caption = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //panel_status_write.Invalidate();
            if (C_MyPipe.SendPipeConnect)
                color_write = Color.DarkGreen;
            else
                color_write = Color.Red;

            if(C_MyPipe.ReadPipeConnect)
                color_read = Color.DarkGreen;
            else
                color_read = Color.Red;
            this.panel_status_read.Invalidate();
            this.panel_status_write.Invalidate();
            //lblPoolStatus.Appearance.ForeColor = 
        }

        int GetStringLength(string str)
        {
            int counter = 0;
            int pos = 0;
            while (pos < str.Length)
            {
                if (str[pos] != ':')
                    counter++;
                pos++;
            }
            return counter;
        }

        /// <summary>
        /// 设备状态图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnState_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FrmState frm = new FrmState();
            frm.MdiParent = this;
            //frm.ControlBox = false;
            frm.Show();    
        }

        /// <summary>
        /// 列控状态图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnState_LK_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        /// <summary>
        /// CTC状态图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnState_CTC_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        /// <summary>
        /// 站场图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnStationMap_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ReadStationCfg();
            //this.bar1.Visible = false;
        }

        void ReadStationCfg()
        {
            string FileName = Application.StartupPath + "\\StartCfg.ini";
            CIniFile IniFile = new CIniFile();
            int RecSum;
            IniFile.SetFileName(FileName);//设置文件名（包括路径）
            IniFile.SetSecName("车站数目");//设置段名
            RecSum = IniFile.GetInt("个数", 0);//读子项目数目
            List<StationPara> lsp = new List<StationPara>();
            for (int i = 1; i <= RecSum; ++i)
            {
                IniFile.SetSecName("车站" + i);//设置段名
                string n = "";
                StationPara sp = new StationPara();
                IniFile.GetString("StationName", ref n, "", 30);
                sp.StationName = n;
                IniFile.GetString("StationCode", ref n, "", 30);
                sp.StationCode = n;
                IniFile.GetString("CFGPath", ref n, "", 30);
                sp.CFGPath = n;
                IniFile.GetString("DatabaseIp", ref n, "", 30);
                sp.DatabaseIp = n;
                lsp.Add(sp);

                LoadStation(sp);
              }
        }
        csds.StationForm sform = null;
        private void LoadStation(csds.StationPara para)
        {
            sform = new csds.StationForm(this, para);
            sform.CMenu_Control_Click += new MyMouseEventHandler(sform_CMenu_Control_Click);
            sform.FLBLEvent += new EventHandler(sform_FLBLEvent);
            sform.MdiParent = this;
            //sform.LayoutMdi(MdiLayout.TileHorizontal);
            ////sform.WindowState = FormWindowState.Maximized;
            Guid guid = Guid.NewGuid();
            sform.guid = guid;
            sform.Text = para.StationName;

            sform.KeyDown += sform_KeyDown;
            sform.Show();
        }

        /// <summary>
        /// 站场图分路不良设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void sform_FLBLEvent(object sender, EventArgs e)
        {           
            FrmFLBL frm = new FrmFLBL();
            frm.Location = MousePosition;
            frm.ShowDialog();
        }

        /// <summary>
        /// 站场图控件对应右键菜单事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void sform_CMenu_Control_Click(object sender, MyMouseEventArgs e)
        {
            FrmDailyTest form = new FrmDailyTest();
            form.ShowDialog();
        }

        void sform_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.bar1.Visible = true;
            }
        }

        private void BtnTest_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FrmDailyTest form = new FrmDailyTest();
            form.ShowDialog();
        }

        /// <summary>
        /// 运用统计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnStatistics_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            splashScreenManager1.ShowWaitForm();
            FormStatistics form = new FormStatistics() { MdiParent = this };
            //form.ControlBox = false;
            form.Show();
            splashScreenManager1.CloseWaitForm();
        }

        private void BtnAlarm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            splashScreenManager1.ShowWaitForm();
            HistroyQXtraForm form = new HistroyQXtraForm();
            form.MdiParent = this;
            //form.ControlBox = false;
            form.Show();
            splashScreenManager1.CloseWaitForm();
        }

        private void BtnReplay_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ReadStationCfg();
            View.HH.ControlBarDlg dlg = new HH.ControlBarDlg();
            dlg.InitStage2();
            dlg.ShowDialog();
        }

        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //DXApplication1.MainForm frm = new DXApplication1.MainForm();
            ////frm.MdiParent = this;
            ////form.ControlBox = false;
            //frm.Show();
        }

        private void btnSwitch_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SwitchForm form = new SwitchForm();
            form.MdiParent = this;
            //form.ControlBox = false;
            form.Show();
        }

        private void btnLog_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            JournalLogForm form = new JournalLogForm();
            form.MdiParent = this;
            //form.ControlBox = false;
            form.Show();
        }

        private void BtnRealAlarm_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FrmRealAlarm frmAlarm = new FrmRealAlarm();
            frmAlarm.Show(this);
        }

        /// <summary>
        /// 报警查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Real_Tick(object sender, EventArgs e)
        {
            if (UtilityFunc.source.Count > 0)
            {
                txtNewAlarm.Caption = UtilityFunc.source.Count + "条新报警";
            }else
            {
                txtNewAlarm.Caption = "";
            }
        }

        void RealTimeValue_NewAlarmEvent(object sender, EventArgs e)
        {
            foreach(ObjAlaram obj in sender as List<ObjAlaram>)
                UtilityFunc.source.Add(MySql.ConvertAlarmObjToDisplay(obj));
        }

        /// <summary>
        /// 系统状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSysStatus_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FrmSysStatus fm = new FrmSysStatus();
            fm.Show(this);
        }

        private Color color_read;
        private Color color_write;

        private void panel_status_write_Paint(object sender, PaintEventArgs e)
        {
            Pen p = new Pen(color_write, 3);

            System.Drawing.Drawing2D.AdjustableArrowCap lineArrow =

                new System.Drawing.Drawing2D.AdjustableArrowCap(4, 4, true);

            p.CustomEndCap = lineArrow;

            e.Graphics.DrawLine(p, new Point(0, 6), new Point(70, 6));
        }

        private void panel_status_read_Paint(object sender, PaintEventArgs e)
        {
            Pen p = new Pen(color_read, 3);

            System.Drawing.Drawing2D.AdjustableArrowCap lineArrow =

                new System.Drawing.Drawing2D.AdjustableArrowCap(4, 4, true);

            p.CustomEndCap = lineArrow;

            e.Graphics.DrawLine(p, new Point(70, 6), new Point(0, 6));
        }
    }
}